package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.dto.DrainageEmployeeDTO;
import com.pactera.madp.cp.api.dto.WorkContactTagUserGroupCreateDTO;
import com.pactera.madp.cp.api.dto.channel.*;
import com.pactera.madp.cp.api.dto.WelcomeMessageDTO;
import com.pactera.madp.cp.api.dto.channel.channelcodeadddtos.*;
import com.pactera.madp.cp.api.dto.workcontacttag.WorkContactTagByChannelCodeDTO;
import com.pactera.madp.cp.api.dto.workcontacttag.WorkContactTagCreateByChannelCodeDTO;
import com.pactera.madp.cp.api.em.permission.ReqPerEnum;
import com.pactera.madp.cp.api.entity.*;
import com.pactera.madp.cp.api.entity.channel.ChannelCodeContactStatisticsEntity;
import com.pactera.madp.cp.api.entity.channel.ChannelCodeEntity;
import com.pactera.madp.cp.api.entity.channel.ChannelCodeGroupEntity;
import com.pactera.madp.cp.api.entity.greeting.GreetingEntity;
import com.pactera.madp.cp.api.entity.medium.MediumEnyity;
import com.pactera.madp.cp.api.vo.channel.*;
import com.pactera.madp.cp.api.page.SubPage;
import com.pactera.madp.cp.api.vo.channel.channelcodedetailsvo.*;
import com.pactera.madp.cp.api.vo.channel.channelcodepagevo.UseEmployeeList;
import com.pactera.madp.cp.common.config.FileUploadConfig;
import com.pactera.madp.cp.common.util.DateUtils;
import com.pactera.madp.cp.common.util.file.FilesUtil;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.job.sync.WorkChannelCodeSyncLogic;
import com.pactera.madp.cp.mapper.channel.ChannelCodeMapper;
import com.pactera.madp.cp.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @author: yangpengwei
 * @time: 2021/2/22 5:06 下午
 * @description 渠道码服务实现类
 */
@Slf4j
@Service
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
public class ChannelCodeServiceImpl extends ServiceImpl<ChannelCodeMapper, ChannelCodeEntity> implements IChannelCodeService {

    @Autowired
    private IChannelCodeGroupService channelCodeGroupService;
    @Autowired
    private IWorkContactEmployeeService contactEmployeeService;
    @Autowired
    private IWorkContactService workContactService;
    @Autowired
    private IWorkEmployeeService workEmployeeService;
    @Autowired
    private IWorkDeptService deptService;
    @Autowired
    private WorkChannelCodeSyncLogic workChannelCodeSyncLogic;
    @Autowired
    private IWorkContactTagService workContactTagService;
    @Autowired
    private IWorkContactTagGroupService workContactTagGroupService;
    @Autowired
    private IBusinessLogService businessLogService;
    @Autowired
    private IWorkEmployeeDepartmentService employeeDepartmentService;
    @Autowired
    private IMediumService mediumService;
    @Autowired
    private FileUploadConfig fileUploadConfig;
    @Autowired
    private ChannelCodeContactStatisticsService channelCodeContactStatisticsService;
    @Autowired
    private IGreetingService greetingService;
    @Autowired
    private IWorkContactTagPivotService workContactTagPivotService;
    @Autowired
    private IWorkContactEmployeeService workContactEmployeeService;
    @Autowired
    private IExternalContactService externalContactService;

    private Map<String, List<?>> checkSpecialDate(DrainageEmployeeDTO.SpecialPeriodDTO employeeDTO) {
        if (2 != employeeDTO.getStatus()) {
            for (DrainageEmployeeDTO.SpecialPeriodDTO.DetailDTO detailDTO :
                    employeeDTO.getDetail()) {
                if (DateUtils.inDateByS3(detailDTO.getStartDate(), detailDTO.getEndDate())) {
                    for (DrainageEmployeeDTO.SpecialPeriodDTO.DetailDTO.TimeSlotDTO timeSlotDTO :
                            detailDTO.getTimeSlot()) {
                        if (DateUtils.inTimeByS5(timeSlotDTO.getStartTime(), timeSlotDTO.getEndTime())) {
                            Map<String, List<?>> map = new HashMap<>(2);
                            // 成员 id 数组
                            map.put("eIds", workEmployeeService.getWxEmpIdListByEmpIdList(timeSlotDTO.getEmployeeId()));
                            // 部门 id 数组
                            map.put("dId", deptService.getWxDeptIdListByDeptIdList(timeSlotDTO.getDepartmentId()));
                            return map;
                        }
                    }
                }
            }
        }
        return null;
    }

    private Map<String, List<?>> checkWeek(DrainageEmployeeDTO drainageEmployeeDTO) {
        for (DrainageEmployeeDTO.EmployeesDTO employeesDTO :
                drainageEmployeeDTO.getEmployees()) {
            if (DateUtils.getDayOfWeek() == employeesDTO.getWeek()) {
                for (DrainageEmployeeDTO.EmployeesDTO.TimeSlotDTO timeSlotDTO :
                        employeesDTO.getTimeSlot()) {
                    if (DateUtils.inTimeByS5(timeSlotDTO.getStartTime(), timeSlotDTO.getEndTime())) {
                        Map<String, List<?>> map = new HashMap<>(2);
                        // 成员 id 数组
                        map.put("eIds", workEmployeeService.getWxEmpIdListByEmpIdList(timeSlotDTO.getEmployeeId()));
                        // 部门 id 数组
                        map.put("dId", deptService.getWxDeptIdListByDeptIdList(timeSlotDTO.getDepartmentId()));
                        return map;
                    }
                }
            }
        }
        return null;
    }

    @Override
    public RespChannelCodeVO getChannelCodeDetail(Integer codeId) {
        ChannelCodeEntity entity = getById(codeId);
        if (Objects.isNull(entity)) {
            throw new CheckedException("渠道码不存在");
        }

        RespChannelCodeVO vo = new RespChannelCodeVO();
        setBaseInfo(entity, vo);
        setDrainageEmployee(entity, vo);
        setWelcomeMessage(entity, vo);
        return vo;
    }

    private void setBaseInfo(ChannelCodeEntity entity, RespChannelCodeVO vo) {
        RespChannelCodeVO.BaseInfoDTO baseInfoDTO = new RespChannelCodeVO.BaseInfoDTO();

        ChannelCodeGroupEntity groupEntity = channelCodeGroupService.getById(entity.getGroupId());
        baseInfoDTO.setGroupId(groupEntity.getId());
        baseInfoDTO.setGroupName(groupEntity.getName());
        baseInfoDTO.setName(entity.getName());
        baseInfoDTO.setAutoAddFriend(entity.getAutoAddFriendStatus());

        List<Integer> tagIdList = JSON.parseArray(entity.getCustomerTagList(), Integer.class);
        baseInfoDTO.setSelectedTags(tagIdList);

        List<WorkContactTagGroupEntity> tagGroupEntityList = workContactTagGroupService.lambdaQuery()
                .eq(WorkContactTagGroupEntity::getCorpId,  CorpContextHolder.getCorpId())
                .list();
        List<RespChannelCodeVO.BaseInfoDTO.TagsDTO> tagsDTOList = new ArrayList<>();
        for (WorkContactTagGroupEntity tagGroupEntity : tagGroupEntityList) {
            RespChannelCodeVO.BaseInfoDTO.TagsDTO tagsDTO = new RespChannelCodeVO.BaseInfoDTO.TagsDTO();
            tagsDTO.setGroupId(tagGroupEntity.getId());
            tagsDTO.setGroupName(tagGroupEntity.getGroupName());

            List<WorkContactTagEntity> tagEntityList = workContactTagService.lambdaQuery()
                    .eq(WorkContactTagEntity::getCorpId, tagGroupEntity.getCorpId())
                    .eq(WorkContactTagEntity::getContactTagGroupId, tagGroupEntity.getId())
                    .list();
            List<RespChannelCodeVO.BaseInfoDTO.TagsDTO.ListDTO> tagDTOList = new ArrayList<>();
            for (WorkContactTagEntity tagEntity : tagEntityList) {
                RespChannelCodeVO.BaseInfoDTO.TagsDTO.ListDTO tagDTO = new RespChannelCodeVO.BaseInfoDTO.TagsDTO.ListDTO();
                tagDTO.setTagId(tagEntity.getId());
                tagDTO.setTagName(tagEntity.getName());
                tagDTO.setIsSelected(tagIdList.contains(tagEntity.getId()) ? 1 : 2);
                tagDTOList.add(tagDTO);
            }

            tagsDTO.setList(tagDTOList);
            tagsDTOList.add(tagsDTO);
        }
        baseInfoDTO.setTags(tagsDTOList);

        vo.setBaseInfo(baseInfoDTO);
    }

    private void setDrainageEmployee(ChannelCodeEntity entity, RespChannelCodeVO vo) {
//        JSONObject drainageEmployeeDTO = JSON.parseObject(entity.getDrainageEmployee());
//        DrainageEmployeeDTO drainageEmployeeDTO =
//                JSON.parseObject(entity.getDrainageEmployee(), DrainageEmployeeDTO.class);
//        vo.setDrainageEmployee(drainageEmployeeDTO);
        vo.setDrainageEmployee(null);
    }

    private void setWelcomeMessage(ChannelCodeEntity entity, RespChannelCodeVO vo) {
//        JSONObject welcomeMessageDTO = JSON.parseObject(entity.getWelcomeMessage());
//        WelcomeMessageDTO welcomeMessageDTO = JSON.parseObject(entity.getDrainageEmployee(), WelcomeMessageDTO.class);
//        vo.setWelcomeMessage(welcomeMessageDTO);
        vo.setWelcomeMessage(null);
    }

    @Override
    public Map<String, Object> getWelcomeMsgMap(Integer channelCodeId,Integer corpId,String externalUserid,Integer employeeId) {
        if (Objects.isNull(channelCodeId)) {
            throw new CheckedException("渠道码 id 不能为空");
        }
        ChannelCodeEntity entity = getOne(Wrappers.<ChannelCodeEntity>lambdaQuery()
                .eq(ChannelCodeEntity::getCorpId,corpId)
                .eq(ChannelCodeEntity::getId,channelCodeId));
        if (entity == null){
            return null;
        }

        //判断当前渠道活码是否有屏蔽词
        log.info("channelCodeId"+channelCodeId);
        log.info("channelCodeCorp:"+corpId);
        log.info("channelCodeEntity:"+entity);
        if (entity.getGreetingShieldStatus().equals(1)){
            List<String> gerttingShield = JSONArray.parseArray(entity.getGreetingShieldList(), String.class);
            AtomicBoolean flags = new AtomicBoolean(false);
            gerttingShield.forEach(g->{
                WorkContactEntity one = workContactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                        .eq(WorkContactEntity::getWxExternalUserid, externalUserid)
                        .eq(WorkContactEntity::getCorpId, corpId).like(WorkContactEntity::getName, g));
                if (one != null){
                    flags.set(true);
                }
            });
            //当 当前添加用户昵称包含屏蔽词时不发送欢迎语
            if (flags.get()){
                return null;
            }else {
                //否则 则发送欢迎语
                HashMap<String, Object> map = new HashMap<>();
                //判断当前欢迎语是否是渠道欢迎语
                if (entity.getGreetingStatus().equals(1)){
                    //判断当前渠道欢迎语是否有分时段欢迎语
                    if (entity.getDaypartingGreetingStatus().equals(1)){
                        List<DaypartingGreetingList> daypartingGreetingLists = JSONArray.parseArray(entity.getDaypartingGreetingList(), DaypartingGreetingList.class);
                        for (DaypartingGreetingList d:daypartingGreetingLists) {
                            AtomicBoolean flag = new AtomicBoolean(false);
                            d.getWeekList().forEach(w->{
                                if (w.equals(DateUtil.dayOfWeek(new Date())-1)){
                                    flag.set(true);
                                }
                            });
                            if (flag.get()){
                                DateTime now = DateTime.now();
                                long time = now.getTime();
                                long startTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + d.getDaypartingGreetingStartTime() + ":00").getTime();
                                long endTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + d.getDaypartingGreetingEndTime() + ":00").getTime();
                                if (time >= startTime && time <= endTime){
                                    MediumEnyity one = mediumService.getOne(Wrappers.<MediumEnyity>lambdaQuery()
                                            .eq(MediumEnyity::getId, d.getMediumId())
                                            .eq(MediumEnyity::getCorpId, corpId));
                                    map.put("text",d.getWords());
                                    if (one != null){
                                        HashMap<String, Object> medium = new HashMap<>();
                                        medium.put("mediumType",one.getType());
                                        medium.put("mediumContent", JSONUtil.parseArray(one.getContent()));
                                        map.put("medium",medium);
                                    }
                                    return map;
                                }
                            }
                        }
                        //写入渠道欢迎语
                        ChannelGreetingMsg channelGreetingMsg = JSONObject.parseObject(entity.getChannelGreetingMsg(), ChannelGreetingMsg.class);
                        MediumEnyity one = mediumService.getOne(Wrappers.<MediumEnyity>lambdaQuery()
                                .eq(MediumEnyity::getId, channelGreetingMsg.getMediumId())
                                .eq(MediumEnyity::getCorpId, corpId));
                        map.put("text",channelGreetingMsg.getWords());
                        if (one != null){
                            HashMap<String, Object> medium = new HashMap<>();
                            medium.put("mediumType",one.getType());
                            medium.put("mediumContent", JSONUtil.parseArray(one.getContent()));
                            map.put("medium",medium);
                        }
                        return map;
                    }else {
                        //写入渠道欢迎语
                        ChannelGreetingMsg channelGreetingMsg = JSONObject.parseObject(entity.getChannelGreetingMsg(), ChannelGreetingMsg.class);
                        map.put("text",channelGreetingMsg.getWords());
                        MediumEnyity one = mediumService.getOne(Wrappers.<MediumEnyity>lambdaQuery()
                                .eq(MediumEnyity::getId, channelGreetingMsg.getMediumId())
                                .eq(MediumEnyity::getCorpId, corpId));
                        if (one != null){
                            HashMap<String, Object> medium = new HashMap<>();
                            medium.put("mediumType",one.getType());
                            medium.put("mediumContent", JSONUtil.parseArray(one.getContent()));
                            map.put("medium",medium);
                        }
                        return map;
                    }
                }else if(entity.getGreetingStatus().equals(2)){
                    //获取成员默认欢迎语
                    List<GreetingEntity> list = greetingService.list(Wrappers.<GreetingEntity>lambdaQuery()
                            .eq(GreetingEntity::getCorpId, corpId).eq(GreetingEntity::getRangeType, 2)
                            .orderByDesc(BaseEntity::getCreateTime));
                    for (GreetingEntity g:list) {
                        String s = g.getDeptIds().replaceAll("\\[", "").replaceAll("\\]", "");
                        String all = s.replaceAll("\"", "").replaceAll("\"", "");
                        String[] split = all.split(",");
                        List<Integer> deptCollect = all.equals("") ? new ArrayList<Integer>() : Arrays.stream(split).map(d->{return Integer.valueOf(d);}).distinct().collect(Collectors.toList());
                        log.info("deptCollect:{}",deptCollect);
                        List<Integer> employeeIds = workEmployeeService.getEmployeeIdsByDeptIds(deptCollect);
                        log.info("employeeIds:{}",employeeIds);
                        if (employeeIds.contains(employeeId)){
                            MediumEnyity one = mediumService.getOne(Wrappers.<MediumEnyity>lambdaQuery()
                                    .eq(MediumEnyity::getId, g.getMediumId())
                                    .eq(MediumEnyity::getCorpId, corpId));
                            map.put("text",g.getWords());
                            if (one != null){
                                HashMap<String, Object> medium = new HashMap<>();
                                medium.put("mediumType",one.getType());
                                medium.put("mediumContent", JSONUtil.parseArray(one.getContent()));
                                map.put("medium",medium);
                            }
                            return map;
                        }
                    }
                }else {
                    //不发送欢迎语
                    return null;
                }
            }
        }else {
            HashMap<String, Object> map = new HashMap<>();
            //判断当前欢迎语是否是渠道欢迎语
            if (entity.getGreetingStatus().equals(1)){
                //判断当前渠道欢迎语是否有分时段欢迎语
                if (entity.getDaypartingGreetingStatus().equals(1)){
                    List<DaypartingGreetingList> daypartingGreetingLists = JSONArray.parseArray(entity.getDaypartingGreetingList(), DaypartingGreetingList.class);
                    for (DaypartingGreetingList d:daypartingGreetingLists) {
                        AtomicBoolean flag = new AtomicBoolean(false);
                        d.getWeekList().forEach(w->{
                            if (w.equals(DateUtil.dayOfWeek(new Date())-1)){
                                flag.set(true);
                            }
                        });
                        if (flag.get()){
                            DateTime now = DateTime.now();
                            long time = now.getTime();
                            long startTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + d.getDaypartingGreetingStartTime() + ":00").getTime();
                            long endTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + d.getDaypartingGreetingEndTime() + ":00").getTime();
                            if (time >= startTime && time <= endTime){
                                MediumEnyity one = mediumService.getOne(Wrappers.<MediumEnyity>lambdaQuery()
                                        .eq(MediumEnyity::getId, d.getMediumId())
                                        .eq(MediumEnyity::getCorpId, corpId));
                                map.put("text",d.getWords());
                                if (one != null){
                                    HashMap<String, Object> medium = new HashMap<>();
                                    medium.put("mediumType",one.getType());
                                    medium.put("mediumContent", JSONUtil.parseArray(one.getContent()));
                                    map.put("medium",medium);
                                }
                                return map;
                            }
                        }
                    }
                    //写入渠道欢迎语
                    ChannelGreetingMsg channelGreetingMsg = JSONObject.parseObject(entity.getChannelGreetingMsg(), ChannelGreetingMsg.class);
                    MediumEnyity one = mediumService.getOne(Wrappers.<MediumEnyity>lambdaQuery()
                            .eq(MediumEnyity::getId, channelGreetingMsg.getMediumId())
                            .eq(MediumEnyity::getCorpId, corpId));
                    map.put("text",channelGreetingMsg.getWords());
                    if (one != null){
                        HashMap<String, Object> medium = new HashMap<>();
                        medium.put("mediumType",one.getType());
                        medium.put("mediumContent", JSONUtil.parseArray(one.getContent()));
                        map.put("medium",medium);
                    }
                    return map;
                }else {
                    //写入渠道欢迎语
                    ChannelGreetingMsg channelGreetingMsg = JSONObject.parseObject(entity.getChannelGreetingMsg(), ChannelGreetingMsg.class);
                    MediumEnyity one = mediumService.getOne(Wrappers.<MediumEnyity>lambdaQuery()
                            .eq(MediumEnyity::getId, channelGreetingMsg.getMediumId())
                            .eq(MediumEnyity::getCorpId, corpId));
                    map.put("text",channelGreetingMsg.getWords());
                    if (one != null){
                        HashMap<String, Object> medium = new HashMap<>();
                        medium.put("mediumType",one.getType());
                        medium.put("mediumContent", JSONUtil.parseArray(one.getContent()));
                        map.put("medium",medium);
                    }
                    return map;
                }
            }else if(entity.getGreetingStatus().equals(2)){
                //获取成员默认欢迎语
                List<GreetingEntity> list = greetingService.list(Wrappers.<GreetingEntity>lambdaQuery()
                        .eq(GreetingEntity::getCorpId, corpId).eq(GreetingEntity::getRangeType, 2)
                        .orderByDesc(BaseEntity::getCreateTime));
                for (GreetingEntity g:list) {
                    String s = g.getDeptIds().replaceAll("\\[", "").replaceAll("\\]", "");
                    String all = s.replaceAll("\"", "").replaceAll("\"", "");
                    String[] split = all.split(",");
                    List<Integer> deptCollect = all.equals("") ? new ArrayList<Integer>() : Arrays.stream(split).map(d->{return Integer.valueOf(d);}).distinct().collect(Collectors.toList());
                    log.info("deptCollect:{}",deptCollect);
                    List<Integer> employeeIds = workEmployeeService.getEmployeeIdsByDeptIds(deptCollect);
                    log.info("employeeIds:{}",employeeIds);
                    if (employeeIds.contains(employeeId)) {
                        MediumEnyity one = mediumService.getOne(Wrappers.<MediumEnyity>lambdaQuery()
                                .eq(MediumEnyity::getId, g.getMediumId())
                                .eq(MediumEnyity::getCorpId, corpId));
                        map.put("text",g.getWords());
                        if (one != null){
                            HashMap<String, Object> medium = new HashMap<>();
                            medium.put("mediumType",one.getType());
                            medium.put("mediumContent", JSONUtil.parseArray(one.getContent()));

                            map.put("medium",medium);
                        }
                        return map;
                    }
                }
            }else {
                //不发送欢迎语
                return null;
            }
        }

        return null;
    }

    private Map<String, String> getWelcomeMessageMap(ChannelCodeEntity channelCodeEntity) {
//        WelcomeMessageDTO welcomeMessageDTO =
//                JSON.parseObject(channelCodeEntity.getWelcomeMessage(), WelcomeMessageDTO.class);
        WelcomeMessageDTO welcomeMessageDTO = new WelcomeMessageDTO();

        boolean open = 1 == welcomeMessageDTO.getScanCodePush();
        if (open) {
            List<WelcomeMessageDTO.MessageDetailDTO> messageDetailDTOList = welcomeMessageDTO.getMessageDetail();
            if (Objects.nonNull(messageDetailDTOList) && messageDetailDTOList.size() > 0) {
                Map<String, String> map = null;
                int size = messageDetailDTOList.size();
                if (3 == size) {
                    WelcomeMessageDTO.MessageDetailDTO messageDetailDTO = messageDetailDTOList.get(2);
                    map = checkWelcomeSpecial(messageDetailDTO);
                }
                if (Objects.isNull(map) || 2 == size) {
                    WelcomeMessageDTO.MessageDetailDTO messageDetailDTO = messageDetailDTOList.get(1);
                    map = checkWelcomeWeek(messageDetailDTO);
                }
                if (Objects.isNull(map) || 1 == size) {
                    WelcomeMessageDTO.MessageDetailDTO messageDetailDTO = messageDetailDTOList.get(0);
                    map = new HashMap<>(2);
                    // 成员 id 数组
                    map.put("welcomeContent", messageDetailDTO.getWelcomeContent());
                    // 部门 id 数组
                    map.put("content", JSON.toJSONString(messageDetailDTO.getContent()));
                }
                return map;
            }
        }
        return null;
    }

    private Map<String, String> checkWelcomeSpecial(WelcomeMessageDTO.MessageDetailDTO messageDetailDTO) {
        if (1 == messageDetailDTO.getStatus()) {
            for (WelcomeMessageDTO.MessageDetailDTO.DetailDTO detailDTO :
                    messageDetailDTO.getDetail()) {
                if (DateUtils.inDateByS3(detailDTO.getStartDate(), detailDTO.getEndDate())) {
                    for (WelcomeMessageDTO.MessageDetailDTO.DetailDTO.TimeSlotDTO timeSlotDTO :
                            detailDTO.getTimeSlot()) {
                        if (DateUtils.inTimeByS5(timeSlotDTO.getStartTime(), timeSlotDTO.getEndTime())) {
                            Map<String, String> map = new HashMap<>(2);
                            // 成员 id 数组
                            map.put("welcomeContent", timeSlotDTO.getWelcomeContent());
                            // 部门 id 数组
                            map.put("content", JSON.toJSONString(timeSlotDTO.getContent()));
                            return map;
                        }
                    }
                }
            }
        }
        return null;
    }

    private Map<String, String> checkWelcomeWeek(WelcomeMessageDTO.MessageDetailDTO messageDetailDTO) {
        if (1 == messageDetailDTO.getStatus()) {
            for (WelcomeMessageDTO.MessageDetailDTO.DetailDTO detailDTO :
                    messageDetailDTO.getDetail()) {
                if (detailDTO.getChooseCycle().contains(DateUtils.getDayOfWeek())) {
                    for (WelcomeMessageDTO.MessageDetailDTO.DetailDTO.TimeSlotDTO timeSlotDTO :
                            detailDTO.getTimeSlot()) {
                        if (DateUtils.inTimeByS5(timeSlotDTO.getStartTime(), timeSlotDTO.getEndTime())) {
                            Map<String, String> map = new HashMap<>(2);
                            // 成员 id 数组
                            map.put("welcomeContent", timeSlotDTO.getWelcomeContent());
                            // 部门 id 数组
                            map.put("content", JSON.toJSONString(timeSlotDTO.getContent()));
                            return map;
                        }
                    }
                }
            }
        }
        return null;
    }


    /**
     * @author: yangpengwei
     * @time: 2021/3/1 3:02 下午
     * @description 编辑渠道码所在分组
     */
    @Override
    public void updateGroupId(Integer codeId, Integer codeGroupId) {
        QueryWrapper<ChannelCodeEntity> codeQueryWrapper = new QueryWrapper<>();
        codeQueryWrapper.eq("corp_id",  CorpContextHolder.getCorpId());
        codeQueryWrapper.eq("id", codeId);
        int codeCount = count(codeQueryWrapper);
        if (codeCount < 1) {
            throw new CheckedException("渠道码 id 不存在");
        }

        if (codeGroupId != 0) {
            QueryWrapper<ChannelCodeGroupEntity> codeGroupQueryWrapper = new QueryWrapper<>();
            codeGroupQueryWrapper.eq("corp_id",  CorpContextHolder.getCorpId());
            codeGroupQueryWrapper.eq("id", codeGroupId);
            int codeGroupCount = channelCodeGroupService.count(codeGroupQueryWrapper);
            if (codeGroupCount < 1) {
                throw new CheckedException("渠道码分组 id 不存在");
            }
        }

        ChannelCodeEntity.builder()
                .id(codeId)
                .corpId( CorpContextHolder.getCorpId())
                .groupId(codeGroupId)
                .build()
                .updateById();
    }

    @Override
    public void updateGroupId(ChannelCodeGroupMoveDTO dto) {
        Integer codeGroupId = dto.getGroupId();
        if (dto.getType() != null && dto.getType().equals(1)){
            List<Integer> channelId    = new LinkedList<>();
            List<ChannelCodeEntity> list = list(Wrappers.<ChannelCodeEntity>lambdaQuery()
                    .eq(ChannelCodeEntity::getCorpId,  CorpContextHolder.getCorpId()));
            list.forEach(l->{
                channelId.add(l.getId());
            });
            dto.setCodeIdList(channelId);
        }
        dto.getCodeIdList().forEach(codeId->{
            QueryWrapper<ChannelCodeEntity> codeQueryWrapper = new QueryWrapper<>();
            codeQueryWrapper.eq("corp_id",  CorpContextHolder.getCorpId());
            codeQueryWrapper.eq("id", codeId);
            int codeCount = count(codeQueryWrapper);
            if (codeCount < 1) {
                throw new CheckedException("渠道码 id 不存在");
            }

            if (codeGroupId != 0) {
                QueryWrapper<ChannelCodeGroupEntity> codeGroupQueryWrapper = new QueryWrapper<>();
                codeGroupQueryWrapper.eq("corp_id",  CorpContextHolder.getCorpId());
                codeGroupQueryWrapper.eq("id", codeGroupId);
                int codeGroupCount = channelCodeGroupService.count(codeGroupQueryWrapper);
                if (codeGroupCount < 1) {
                    throw new CheckedException("渠道码分组 id 不存在");
                }
            }

            ChannelCodeEntity.builder()
                    .id(codeId)
                    .corpId( CorpContextHolder.getCorpId())
                    .groupId(codeGroupId)
                    .build()
                    .updateById();
        });
    }

    /**
     * @author: yangpengwei
     * @time: 2021/3/1 3:00 下午
     * @description 获取渠道码 - 客户列表
     * @return
     */
    @Override
    public R getChannelCodeContactByReq(Integer channelCodeId, Page page) {
        QueryWrapper<WorkContactEmployeeEntity> queryContactEmployeeWrapper = Wrappers.query();
        queryContactEmployeeWrapper.select("contact_id c_id", "GROUP_CONCAT(employee_id) e_ids");
        queryContactEmployeeWrapper.eq("state", "channelCodeId-" + channelCodeId);
        queryContactEmployeeWrapper.eq("corp_id",  CorpContextHolder.getCorpId());
        queryContactEmployeeWrapper.groupBy("contact_id");
//        Page<Map<String, Object>> pageQuery = ApiRespUtils.initPage(page);
        contactEmployeeService.pageMaps(page, queryContactEmployeeWrapper);

//        Page<RespChannelCodeContactVO> pageResult = ApiRespUtils.initPage(page);
        List<RespChannelCodeContactVO> voList = new ArrayList<>();
        List<Map> list = page.getRecords();
        for (Map<String, Object> map : list) {
            RespChannelCodeContactVO vo = new RespChannelCodeContactVO();

            String cId = map.get("c_id").toString();
            String eIds = map.get("e_ids").toString();

            List<String> eIdList = Arrays.asList(eIds.split(","));
            QueryWrapper<WorkEmployeeEntity> queryEmployeeWrapper = Wrappers.query();
            queryEmployeeWrapper.select("GROUP_CONCAT(`name`) `name`");
            queryEmployeeWrapper.in("id", eIdList);
            queryEmployeeWrapper.eq("corp_id",  CorpContextHolder.getCorpId());
            List<Map<String, Object>> eListMap = workEmployeeService.listMaps(queryEmployeeWrapper);
            String names = "";
            if (!eListMap.isEmpty()) {
                names = eListMap.get(0).get("name").toString();
            }

            // 查询客户名
            WorkContactEntity contactEntity = workContactService.getById(cId);
            vo.setContactId(contactEntity.getId());
            vo.setName(contactEntity.getName());
            vo.setEmployees(Arrays.asList(names.split(",")));
            vo.setCreateTime(contactEntity.getCreateTime().toString());
            voList.add(vo);
        }
        SubPage subPage = new SubPage();
        subPage.setRecords(voList);
        subPage.setCurrent(page.getCurrent());
        subPage.setSize(page.getSize());
        subPage.setTotal(page.getTotal());

        return R.ok(subPage);
    }

    /**
     * @author: yangpengwei
     * @time: 2021/3/1 3:00 下午
     * @description 获取渠道码列表
     */
    @Override
    public R getChannelCodePageByReq(ReqChannelCodeListDTO req, Page page, ReqPerEnum permission) {
//
////        Page<ChannelCodeEntity> codeEntityPage = ApiRespUtils.initPage(page);
//        LambdaQueryChainWrapper<ChannelCodeEntity> lambdaQueryWrapper = lambdaQuery();
//        // 权限管理查询配置
//        setWrapperPermission(lambdaQueryWrapper, permission);
//
//        lambdaQueryWrapper.eq(ChannelCodeEntity::getCorpId,  CorpContextHolder.getCorpId());
//
//        String name = req.getName();
//        if (StringUtils.hasLength(name)) {
//            lambdaQueryWrapper.like(ChannelCodeEntity::getName, name);
//        }
//
//        Integer type = req.getType();
//        if (!Objects.isNull(type) && type > 0 && type < 3) {
//            lambdaQueryWrapper.eq(ChannelCodeEntity::getType, type);
//        }
//
//        Integer groupId = req.getGroupId();
//        if (!Objects.isNull(groupId)) {
//            lambdaQueryWrapper.eq(ChannelCodeEntity::getGroupId, groupId);
//        }
//
//        lambdaQueryWrapper.page(page);
//
//        List<ChannelCodeEntity> codeEntityList = page.getRecords();
//        List<RespChannelCodeListVO> voList = new ArrayList<>();
//        for (ChannelCodeEntity e : codeEntityList) {
//            RespChannelCodeListVO vo = new RespChannelCodeListVO();
//            vo.setChannelCodeId(e.getId());
//            vo.setQrcodeUrl(AliyunOssUtils.getUrl(e.getQrcodeUrl()));
//            vo.setName(e.getName());
//
//            String typeStr = "";
//            if (1 == e.getType()) {
//                typeStr = "单人";
//            } else if (2 == e.getType()) {
//                typeStr = "多人";
//            }
//            vo.setType(typeStr);
//
//            ChannelCodeGroupEntity groupEntity = channelCodeGroupService.getById(e.getGroupId());
//            if (Objects.isNull(groupEntity)) {
//                vo.setGroupName("未分组");
//            } else {
//                vo.setGroupName(groupEntity.getName());
//            }
//
//            int countNum = contactEmployeeService.lambdaQuery()
//                    .eq(WorkContactEmployeeEntity::getCorpId,  CorpContextHolder.getCorpId())
//                    .eq(WorkContactEmployeeEntity::getState, "channelCodeId-" + e.getId())
//                    .count();
//            vo.setContactNum(countNum);
//
//            List<String> tagNames = new ArrayList<>();
//            List<Integer> tagIdList = JSON.parseArray(e.getTags(), Integer.class);
//            if (!Objects.isNull(tagIdList) && !tagIdList.isEmpty()) {
//                List<WorkContactTagEntity> tagEntityList = (List<WorkContactTagEntity>) workContactTagService.listByIds(tagIdList);
//                tagNames.addAll(tagEntityList.stream().map(WorkContactTagEntity::getName).collect(Collectors.toList()));
//                vo.setTags(tagNames);
//            }
//            vo.setTags(tagNames);
//            vo.setAutoAddFriend(e.getAutoAddFriend() == 1 ? "自动添加好友" : "验证添加好友");
//            voList.add(vo);
//        }
        SubPage subPage = new SubPage();
//        subPage.setRecords(voList);
        subPage.setCurrent(page.getCurrent());
        subPage.setSize(page.getSize());
        subPage.setTotal(page.getTotal());
        return R.ok(subPage);
    }

    /**
     * @author: yangpengwei
     * @time: 2021/3/17 11:19 上午
     * @description 权限管理查询条件配置
     */
//    private void setWrapperPermission(LambdaQueryChainWrapper<ChannelCodeEntity> wrapper, ReqPerEnum permission) {
//        if (permission == ReqPerEnum.ALL) {
//            return;
//        }
//
//        LambdaQueryChainWrapper<BusinessLogEntity> logWrapper = businessLogService.lambdaQuery();
//        if (permission == ReqPerEnum.DEPARTMENT) {
//            // 查询员工所属的部门 id 列表
//            List<Integer> idList = employeeDepartmentService.getDeptAndChildDeptEmpIdList();
//            logWrapper.in(BusinessLogEntity::getOperationId, idList);
//        }
//
//        if (permission == ReqPerEnum.EMPLOYEE) {
//            int empId =  e.getEmpId();
//            logWrapper.eq(BusinessLogEntity::getOperationId, empId);
//        }
//
//        // 渠道码业务 id 列表 (渠道码 id 列表)
//        List<Integer> idList = logWrapper.in(
//                BusinessLogEntity::getEvent,
//                Arrays.asList(EventEnum.CHANNEL_CODE_CREATE.getCode(), EventEnum.CHANNEL_CODE_UPDATE.getCode())
//        ).list().stream().map(BusinessLogEntity::getBusinessId).collect(Collectors.toList());
//
//        if (idList.isEmpty()) {
//            wrapper.eq(ChannelCodeEntity::getId, -1);
//        } else {
//            wrapper.in(ChannelCodeEntity::getId, idList);
//        }
//    }

    @Override
    public void updateChannelCodeQr(Integer channelCodeId, Integer corpId) {
        ChannelCodeEntity entity = getOne(Wrappers.<ChannelCodeEntity>lambdaQuery()
                .eq(ChannelCodeEntity::getCorpId,corpId)
                .eq(ChannelCodeEntity::getId,channelCodeId));
        List<ChannelCodeContactStatisticsEntity> entityList = channelCodeContactStatisticsService.list(Wrappers.<ChannelCodeContactStatisticsEntity>lambdaQuery()
                .eq(ChannelCodeContactStatisticsEntity::getChannelId, channelCodeId)
                .eq(ChannelCodeContactStatisticsEntity::getCorpId, corpId)
                .ge(BaseEntity::getCreateTime,DateUtil.beginOfDay(new Date()))
                .le(BaseEntity::getCreateTime,DateUtil.endOfDay(new Date())));
        Map<String, List<?>> map = new HashMap<>();
        //判断当前成员是否为全天在线
        if (entity != null) {
            if (entity.getCustomerServicePersonnelStatus().equals(1)){
                List<EmployeeIdList> list = JSONArray.parseArray(entity.getEmployeeAllDayLongList(), EmployeeIdList.class);
                List<Integer> empIds = new LinkedList<>();
                List<Integer> list1 = new LinkedList<>();
                List<Integer> list2 = new LinkedList<>();
                //获取全天在线成员的id列表
                list.forEach(l -> {
                    if (l.getStatus().equals(1)){
                        list1.add(l.getId());
                    }
                });
                //判断当前渠道活码是否有成员每天添加上限值
                if (entity.getEmployeeAddUpperLimitStatus().equals(1)){
                    List<EmployeeAddUpperLimitList> lists = JSONArray.parseArray(entity.getEmployeeAddUpperLimitList(), EmployeeAddUpperLimitList.class);
                    lists.forEach(l->{
                        entityList.forEach(en->{
                            list1.forEach(e->{
                                if (en.getEmployeeId().equals(e) && en.getNewAddContact() >= l.getMaxNum() && l.getEmployeeId().equals(en.getEmployeeId())){
                                    list2.add(e);
                                }
                            });
                        });
                    });
                }
                HashSet hs1 = new HashSet(list1);
                HashSet hs2 = new HashSet(list2);
                hs1.removeAll(hs2);
                empIds.addAll(hs1);

                //如果所有在线成员添加达到上限则启用备用成员
                if (empIds.isEmpty()){
                    List<Integer> array = JSONArray.parseArray(entity.getStandbyEmployeeList(), Integer.class);
                    empIds.addAll(array);
                }
                //将符合条件的成员微信userid封装
                List<WorkEmployeeEntity> employeeEntities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .eq(WorkEmployeeEntity::getCorpId, entity.getCorpId())
                        .in(WorkEmployeeEntity::getId, empIds));
                List<String> eIds = new LinkedList<>();
                employeeEntities.forEach(e->{
                    eIds.add(e.getWxUserId());
                });
                map.put("eIds",eIds);
            } else {
                //当成员为自动上下线时进行如下处理
                List<EmployeeTopBottomLineLists> topBottomLineLists = JSONArray.parseArray(entity.getEmployeeTopBottomLineList(), EmployeeTopBottomLineLists.class);
                List<Integer> empList = new LinkedList<>();
                topBottomLineLists.forEach(top->{
                    int i = DateUtil.dayOfWeek(new Date())-1;
                    boolean flag = false;
                    for (Integer week:top.getWeekList()){
                        if (week.equals(i)){
                            flag = true;
                            break;
                        }
                    }
                    //判断当前时段是否有成员在线
                    if (flag){
                        DateTime now = DateTime.now();
                        long time = now.getTime();
                        long startTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + top.getEmployeeTopBottomLineStartTime() + ":00").getTime();
                        long endTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + top.getEmployeeTopBottomLineEndTime() + ":00").getTime();
                        if (time >= startTime && time <= endTime){
                            top.getEmployeeIdList().forEach(em->{
                                if (em.getStatus().equals(1)){
                                    empList.add(em.getId());
                                }
                            });

                        }
                    }
                });
                //当前时段没人在线时启用备用成员
                if (empList.isEmpty()){
                    List<WorkEmployeeEntity> entities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                            .eq(WorkEmployeeEntity::getCorpId, entity.getCorpId())
                            .in(WorkEmployeeEntity::getId, JSONArray.parseArray(entity.getStandbyEmployeeList(),Integer.class)));
                    List<String> eIds  = new LinkedList<>();
                    entities.forEach(e->{
                        eIds.add(e.getWxUserId());
                    });
                    map.put("eIds",eIds);
                } else {
                    //当前时段有成员在线时进行如下处理
                    List<Integer> list1 = empList.stream().distinct().collect(Collectors.toList());
                    List<Integer> list2 = new LinkedList<>();
                    List<Integer> collect = new LinkedList<>();

                    //判断当前渠道活码是否有成员每天添加上限值
                    if (entity.getEmployeeAddUpperLimitStatus().equals(1)){
                        List<EmployeeAddUpperLimitList> lists = JSONArray.parseArray(entity.getEmployeeAddUpperLimitList(), EmployeeAddUpperLimitList.class);
                        lists.forEach(l->{
                            entityList.forEach(en->{
                                list1.forEach(e->{
                                    if (en.getEmployeeId().equals(e) && en.getNewAddContact() >= l.getMaxNum() && l.getEmployeeId().equals(en.getEmployeeId())){
                                        list2.add(e);
                                    }
                                });
                            });
                        });
                    }
                    HashSet hs1 = new HashSet(list1);
                    HashSet hs2 = new HashSet(list2);
                    hs1.removeAll(hs2);
                    collect.addAll(hs1);

                    //如果所有在线成员添加达到上限则启用备用成员
                    if (collect.isEmpty()){
                        List<Integer> array = JSONArray.parseArray(entity.getStandbyEmployeeList(), Integer.class);
                        collect.addAll(array);
                    }

                    //将符合条件的成员微信userid封装
                    List<WorkEmployeeEntity> entities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                            .eq(WorkEmployeeEntity::getCorpId, entity.getCorpId())
                            .in(WorkEmployeeEntity::getId, collect));
                    List<String> eIds  = new LinkedList<>();
                    entities.forEach(e->{
                        eIds.add(e.getWxUserId());
                    });
                    map.put("eIds",eIds);
                }
            }

            workChannelCodeSyncLogic.onUpdateWxAddContactWayQrcode(entity.getId(), map);
        }
    }

    /*@Override
    public boolean createChannelCode(ChannelCodeAddDTO channelCodeAddDTO) {
        List<ChannelCodeEntity> codeEntities = list(Wrappers.<ChannelCodeEntity>lambdaQuery()
                .eq(ChannelCodeEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(ChannelCodeEntity::getName, channelCodeAddDTO.getName()));
        if (!codeEntities.isEmpty()) {
            throw new CheckedException("当前渠道活码名字重复");
        }

        HashMap<String, List<?>> map = new HashMap<>();
        ChannelCodeEntity entity = new ChannelCodeEntity();
        entity.setCorpId(CorpContextHolder.getCorpId());
        BeanUtil.copyProperties(channelCodeAddDTO, entity);
        preHandlerDto(channelCodeAddDTO, entity);

        entity.setCreateTime(DateUtil.toLocalDateTime(DateTime.now()));
        boolean save = save(entity);
        if (!save) {
            return false;
        }
        if (entity.getCustomerServicePersonnelStatus().equals(1)) {
            List<EmployeeIdList> list = channelCodeAddDTO.getEmployeeAllDayLongList();
            List<Integer> empIds = new LinkedList<>();
            list.forEach(l -> {
                if (l.getStatus().equals(1)) {
                    empIds.add(l.getId());
                }
            });
            List<WorkEmployeeEntity> entities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .in(WorkEmployeeEntity::getId, empIds)
                    .eq(WorkEmployeeEntity::getCorpId, CorpContextHolder.getCorpId()));
            List<String> eIds = new LinkedList<>();
            entities.forEach(e -> {
                eIds.add(e.getWxUserId());
            });
            map.put("eIds", eIds);
        } else {
            List<EmployeeTopBottomLineLists> topBottomLineLists = channelCodeAddDTO.getEmployeeTopBottomLineList();
            List<Integer> empList = new LinkedList<>();
            topBottomLineLists.forEach(top -> {
                int i = DateUtil.dayOfWeek(new Date()) - 1;
                boolean flag = false;
                for (Integer week:top.getWeekList()) {
                    if (week.equals(i)) {
                        flag = true;
                        break;
                    }
                }
                //判断当前时段是否有成员在线
                if (flag) {
                    DateTime now = DateTime.now();
                    long time = now.getTime();
                    long startTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + top.getEmployeeTopBottomLineStartTime() + ":00").getTime();
                    long endTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + top.getEmployeeTopBottomLineEndTime() + ":00").getTime();
                    if (time >= startTime && time <= endTime) {
                        top.getEmployeeIdList().forEach(em -> {
                            if (em.getStatus().equals(1)) {
                                empList.add(em.getId());
                            }
                        });

                    }
                }
            });
            //当前时段没人在线时启用备用成员
            if (empList.isEmpty()) {
                List<WorkEmployeeEntity> entities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .eq(WorkEmployeeEntity::getCorpId, entity.getCorpId())
                        .in(WorkEmployeeEntity::getId, JSONArray.parseArray(entity.getStandbyEmployeeList(),Integer.class)));
                List<String> eIds  = new LinkedList<>();
                entities.forEach(e -> {
                    eIds.add(e.getWxUserId());
                });
                map.put("eIds", eIds);
            } else {
                //当前时段有成员在线时进行如下处理
                List<Integer> list1 = empList.stream().distinct().collect(Collectors.toList());
                //将符合条件的成员微信userid封装
                List<WorkEmployeeEntity> entities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .eq(WorkEmployeeEntity::getCorpId, entity.getCorpId())
                        .in(WorkEmployeeEntity::getId, list1));
                List<String> eIds  = new LinkedList<>();
                entities.forEach(e -> {
                    eIds.add(e.getWxUserId());
                });
                map.put("eIds", eIds);
            }
        }
        return workChannelCodeSyncLogic.onCreateWxAddContactWayQrcode(entity, map);
    }*/

    private void checkNameUnique(String name) {
        List<ChannelCodeEntity> codeEntities = list(Wrappers.<ChannelCodeEntity>lambdaQuery()
                .eq(ChannelCodeEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(ChannelCodeEntity::getName, name));
        if (!codeEntities.isEmpty()) {
            throw new CheckedException("当前渠道活码名字重复");
        }
    }

    @Override
    public boolean createChannelCode(ChannelCodeAddDTO channelCodeAddDTO) {
        // 检验渠道活码名字唯一性
        checkNameUnique(channelCodeAddDTO.getName());

        HashMap<String, List<?>> map = new HashMap<>();
        ChannelCodeEntity entity = new ChannelCodeEntity();
        entity.setCorpId(CorpContextHolder.getCorpId());
        BeanUtil.copyProperties(channelCodeAddDTO, entity);
        preHandleAddDto(channelCodeAddDTO, entity);

        entity.setCreateTime(DateUtil.toLocalDateTime(DateTime.now()));
        boolean save = save(entity);
        if (!save) {
            return false;
        }
        LambdaQueryWrapper<WorkEmployeeEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WorkEmployeeEntity::getCorpId, entity.getCorpId());
        // 若客服人员状态为1-全天在线
        if (entity.getCustomerServicePersonnelStatus().equals(1)) {
            List<Integer> empIds = channelCodeAddDTO.getEmployeeAllDayLongList()
                    .stream()
                    .filter(s -> s.getStatus().equals(1))
                    .map(EmployeeIdList::getId)
                    .collect(Collectors.toList());
            wrapper.in(WorkEmployeeEntity::getId, empIds);
        }/* else {
            // 否则客服人员状态为2-自动上下线
            // 获取员工自动上下线列表（工作周期列表）
            List<EmployeeTopBottomLineLists> topBottomLineLists = channelCodeAddDTO.getEmployeeTopBottomLineList();
            List<Integer> empList = new LinkedList<>();

            DateTime now = DateTime.now();
            // 获取今天是周几
            int i = now.dayOfWeek() - 1;
            // 遍历工作周期列表
            topBottomLineLists.forEach(top -> {
                boolean flag = false;
                for (Integer week : top.getWeekList()) {
                    if (week.equals(i)) {
                        // 今天属于当前工作周期
                        flag = true;
                        break;
                    }
                }
                // 判断当前时段是否有成员在线
                if (flag) {
                    long time = now.getTime();
                    long startTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + top.getEmployeeTopBottomLineStartTime() + ":00").getTime();
                    long endTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + top.getEmployeeTopBottomLineEndTime() + ":00").getTime();
                    if (time >= startTime && time <= endTime) {
                        top.getEmployeeIdList().forEach(em -> {
                            if (em.getStatus().equals(1)) {
                                empList.add(em.getId());
                            }
                        });

                    }
                }
            });
            //当前时段没人在线时启用备用成员
            if (empList.isEmpty()) {
                wrapper.in(WorkEmployeeEntity::getId, JSONArray.parseArray(entity.getStandbyEmployeeList(), Integer.class));
            } else {
                //当前时段有成员在线时进行如下处理
                List<Integer> list1 = empList.stream().distinct().collect(Collectors.toList());
                //将符合条件的成员微信userid封装
                wrapper.in(WorkEmployeeEntity::getId, list1);
            }
        }*/
        List<String> eIds = workEmployeeService.list(wrapper)
                .stream().map(WorkEmployeeEntity::getWxUserId).collect(Collectors.toList());
        map.put("eIds", eIds);
        return workChannelCodeSyncLogic.onCreateWxAddContactWayQrcode(entity, map);
    }

    private void preHandleAddDto(ChannelCodeAddDTO channelCodeAddDTO, ChannelCodeEntity entity) {
        //判断当前欢迎语是否为渠道欢迎语
        if (channelCodeAddDTO.getGreetingStatus().equals(1)) {
            entity.setChannelGreetingMsg(JSONUtil.toJsonStr(channelCodeAddDTO.getChannelGreetingMsg()));
            //判断当前渠道欢迎语是否有分时段渠道欢迎语
            if (channelCodeAddDTO.getDaypartingGreetingStatus().equals(1)) {
                entity.setDaypartingGreetingList(JSONUtil.toJsonStr(channelCodeAddDTO.getDaypartingGreetingList()));
            } else {
                entity.setDaypartingGreetingList(null);
            }
        } else {
            entity.setChannelGreetingMsg(null);
            entity.setDaypartingGreetingList(null);
        }

        //判断当前渠道活码是否为自动同意好友申请
        if (channelCodeAddDTO.getAutoAddFriendStatus().equals(1)) {
            //判断当前自动通过好友状态是否为分时间段同意好友申请
            if (channelCodeAddDTO.getAutoAddFriendTimeStatus().equals(2)) {
                entity.setAutoAddFriendMsg(JSONUtil.toJsonStr(channelCodeAddDTO.getAutoAddFriendMsg()));
            } else {
                entity.setAutoAddFriendMsg(null);
            }
        } else {
            entity.setAutoAddFriendMsg(null);
        }

        //判断该渠道活码是否有标签
        if (channelCodeAddDTO.getCustomerTagStatus().equals(1)) {
            entity.setCustomerTagList(JSONUtil.toJsonStr(channelCodeAddDTO.getCustomerTagList()));
        } else {
            entity.setCustomerTagList(null);
        }

        //判断客服人员是否会自动上下线
        if (channelCodeAddDTO.getCustomerServicePersonnelStatus().equals(2)) {
            entity.setEmployeeTopBottomLineList(JSONUtil.toJsonStr(channelCodeAddDTO.getEmployeeTopBottomLineList()));
            entity.setEmployeeAllDayLongList(null);
        } else {
            entity.setEmployeeTopBottomLineList(null);
            entity.setEmployeeAllDayLongList(JSONUtil.toJsonStr(channelCodeAddDTO.getEmployeeAllDayLongList()));
        }

        //判断客服人员是否有添加客户上限
        if (channelCodeAddDTO.getEmployeeAddUpperLimitStatus().equals(1)) {
            entity.setEmployeeAddUpperLimitList(JSONUtil.toJsonStr(channelCodeAddDTO.getEmployeeAddUpperLimitList()));
        } else {
            entity.setEmployeeAddUpperLimitList(null);
        }

        //判断该渠道活码是否有欢迎语屏蔽词
        if (channelCodeAddDTO.getGreetingShieldStatus().equals(1)) {
            entity.setGreetingShieldList(JSONUtil.toJsonStr(channelCodeAddDTO.getGreetingShieldList()));
        } else {
            entity.setGreetingShieldList(null);
        }
    }

    private void preHandleUpdateDto(ChannelCodeUpdateDTO channelCodeUpdateDTO, ChannelCodeEntity entity) {
        if (channelCodeUpdateDTO.getGreetingStatus().equals(1)) {
            entity.setChannelGreetingMsg(JSONUtil.toJsonStr(channelCodeUpdateDTO.getChannelGreetingMsg()));
        } else {
            entity.setChannelGreetingMsg(null);
        }

        if (channelCodeUpdateDTO.getAutoAddFriendTimeStatus().equals(2)) {
            entity.setAutoAddFriendMsg(JSONUtil.toJsonStr(channelCodeUpdateDTO.getAutoAddFriendMsg()));
        } else {
            entity.setAutoAddFriendMsg(null);
        }

        if (channelCodeUpdateDTO.getCustomerTagStatus().equals(1)) {
            entity.setCustomerTagList(JSONUtil.toJsonStr(channelCodeUpdateDTO.getCustomerTagList()));
        } else {
            entity.setCustomerTagList(null);
        }

        if (channelCodeUpdateDTO.getDaypartingGreetingStatus().equals(1)) {
            entity.setDaypartingGreetingList(JSONUtil.toJsonStr(channelCodeUpdateDTO.getDaypartingGreetingList()));
        } else {
            entity.setDaypartingGreetingList(null);
        }
        if (channelCodeUpdateDTO.getEmployeeAddUpperLimitStatus().equals(1)) {
            entity.setEmployeeAddUpperLimitList(JSONUtil.toJsonStr(channelCodeUpdateDTO.getEmployeeAddUpperLimitList()));
        } else {
            entity.setEmployeeAddUpperLimitList(null);
        }
        if (channelCodeUpdateDTO.getGreetingShieldStatus().equals(1)) {
            entity.setGreetingShieldList(JSONUtil.toJsonStr(channelCodeUpdateDTO.getGreetingShieldList()));
        } else {
            entity.setGreetingShieldList(null);
        }
    }

    @Override
    public IPage<ChannelCodePageVO> pageList(ChannelCodePageDTO dto,Page page) {
        QueryWrapper<ChannelCodeEntity> wrapper = new QueryWrapper<>();
        if (!StrUtil.isBlank(dto.getName())){
            wrapper.like("name",dto.getName());
        }
        if (dto.getGroupId() != null){
            wrapper.eq("group_id",dto.getGroupId());
        }
        wrapper.eq("corp_id", CorpContextHolder.getCorpId());
        wrapper.orderByDesc("create_time");
        IPage iPage = page(page, wrapper);
        List<ChannelCodeEntity> records = iPage.getRecords();
        List<ChannelCodePageVO> vos = new LinkedList<>();
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        records.forEach(r->{
            ChannelCodePageVO vo = new ChannelCodePageVO();
//            channelCodeContactStatisticsService.list(Wrappers.<ChannelCodeContactStatisticsEntity>lambdaQuery()
//                    .eq(ChannelCodeContactStatisticsEntity::getCorpId,r.getCorpId())
//                    .eq(ChannelCodeContactStatisticsEntity::getChannelId,r.getId())
//                    .ge(BaseEntity::getCreateTime,)
//                    .le(BaseEntity::getCreateTime,))
            QueryWrapper<ChannelCodeContactStatisticsEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("sum(all_contact) as allAddContact");
            queryWrapper.eq("corp_id",r.getCorpId());
            queryWrapper.eq("channel_id",r.getId());
            queryWrapper.ge("create_time",DateUtil.beginOfDay(new Date()));
            queryWrapper.le("create_time",DateUtil.endOfDay(new Date()));
            Map<String, Object> map = channelCodeContactStatisticsService.getMap(queryWrapper);
            vo.setCount(map == null ? 0 : Integer.parseInt(map.get("allAddContact").toString()));
            BeanUtil.copyProperties(r,vo);
            vo.setCreateTime(pattern.format(r.getCreateTime()));
            //设置客户标签
            if (r.getCustomerTagStatus().equals(1)){
                List<WorkContactTagUserGroupCreateDTO> tagDTOS = JSONArray.parseArray(r.getCustomerTagList(), WorkContactTagUserGroupCreateDTO.class);
                List<String> tags = new LinkedList<>();
                tagDTOS.forEach(tag->{
                    tag.getTagNameList().forEach(t->{
                        WorkContactTagEntity one = workContactTagService.getOne(Wrappers.<WorkContactTagEntity>lambdaQuery()
                                .eq(WorkContactTagEntity::getCorpId,  CorpContextHolder.getCorpId())
//                                .eq(WorkContactTagEntity::getWxContactTagId, t.getWxContactTagId())
                                .eq(WorkContactTagEntity::getId, t.getId())
                        );
                        if (one != null){
                            tags.add(one.getName());
                        }
                    });
                });
                vo.setTags(tags);
            }
            List<UseEmployeeList> useEmployeeLists = new LinkedList<>();

            //设置成员列表信息
            if (r.getCustomerServicePersonnelStatus().equals(1)){
                List<EmployeeIdList> parseArray = JSONArray.parseArray(r.getEmployeeAllDayLongList(), EmployeeIdList.class);
                parseArray.forEach(p->{
                    WorkEmployeeEntity entity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                            .eq(WorkEmployeeEntity::getCorpId,  CorpContextHolder.getCorpId())
                            .eq(WorkEmployeeEntity::getId, p.getId()));
                    if (entity != null){
                        UseEmployeeList list = new UseEmployeeList();
                        list.setUseEmployeeId(entity.getId());
                        list.setUserEmployeeName(entity.getName());
                        list.setStatus(p.getStatus());
                        useEmployeeLists.add(list);
                    }
                });
            }else {
                List<EmployeeTopBottomLineLists> topBottomLineLists = JSONArray.parseArray(r.getEmployeeTopBottomLineList(), EmployeeTopBottomLineLists.class);
                topBottomLineLists.forEach(top->{
                    List<Integer> empIds = new LinkedList<>();
                    top.getEmployeeIdList().forEach(e->{
                        if (e.getStatus().equals(1)){
                            empIds.add(e.getId());
                        }
                    });
                    List<WorkEmployeeEntity> entities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                            .eq(WorkEmployeeEntity::getCorpId,  CorpContextHolder.getCorpId())
                            .in(WorkEmployeeEntity::getId, empIds));

                    int i = DateUtil.dayOfWeek(new Date())-1;
                    boolean flag = false;
                    for (Integer week:top.getWeekList()){
                        if (week.equals(i)){
                            flag = true;
                            break;
                        }
                    }
                    if (flag){
                        DateTime now = DateTime.now();
                        long time = now.getTime();
                        long startTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + top.getEmployeeTopBottomLineStartTime() + ":00").getTime();
                        long endTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + top.getEmployeeTopBottomLineEndTime() + ":00").getTime();
                        if (time >= startTime && time <= endTime){
                            entities.forEach(en->{
                                UseEmployeeList useEmployeeList = new UseEmployeeList();
                                useEmployeeList.setUseEmployeeId(en.getId());
                                useEmployeeList.setUserEmployeeName(en.getName());
                                useEmployeeList.setStatus(1);
                                useEmployeeLists.add(useEmployeeList);
                            });
                        }else {
                            entities.forEach(en->{
                                UseEmployeeList useEmployeeList = new UseEmployeeList();
                                useEmployeeList.setUseEmployeeId(en.getId());
                                useEmployeeList.setUserEmployeeName(en.getName());
                                useEmployeeList.setStatus(2);
                                useEmployeeLists.add(useEmployeeList);
                            });
                        }
                    }else {
                        entities.forEach(en->{
                            UseEmployeeList useEmployeeList = new UseEmployeeList();
                            useEmployeeList.setUseEmployeeId(en.getId());
                            useEmployeeList.setUserEmployeeName(en.getName());
                            useEmployeeList.setStatus(2);
                            useEmployeeLists.add(useEmployeeList);
                        });
                    }
                });
            }

//            List<WorkEmployeeEntity> entities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
//                    .eq(WorkEmployeeEntity::getCorpId,  CorpContextHolder.getCorpId())
//                    .in(WorkEmployeeEntity::getId, JSONArray.parseArray(r.getStandbyEmployeeList(),Integer.class)));
//            LinkedList<StandbyEmployeeList> standbyEmployeeLists = new LinkedList<>();
//            entities.forEach(et->{
//                StandbyEmployeeList list = new StandbyEmployeeList();
//                list.setStandbyEmployeeName(et.getName());
//                list.setStandbyEmployeeId(et.getId());
//                standbyEmployeeLists.add(list);
//            });

//            vo.setStandbyEmployeeList(standbyEmployeeLists);
            vo.setUseEmployeeListList(useEmployeeLists);
            vos.add(vo);
        });
        iPage.setRecords(vos);
        return iPage;
    }

    @Override
    public boolean deleteChannelCode(Integer id) {
        return removeById(id);
    }

    @Override
    public ChannelCodeDetailsVO channelCodeDetailsById(Integer id) {
        ChannelCodeEntity entity = getOne(Wrappers.<ChannelCodeEntity>lambdaQuery()
                .eq(ChannelCodeEntity::getCorpId,  CorpContextHolder.getCorpId())
                .eq(ChannelCodeEntity::getId, id));
        ChannelCodeDetailsVO vo = new ChannelCodeDetailsVO();
        BeanUtil.copyProperties(entity,vo);
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        vo.setCreateTime(pattern.format(entity.getCreateTime()));

        //设置在线、下线列表值、设置全天在线员工列表、设置自动上下线员工列表
        if (vo.getCustomerServicePersonnelStatus().equals(1)){
            LinkedList<EmployeeAllDayLongListByDetails> allDayLongLists = new LinkedList<>();
            List<EmployeeIdList> listList = JSONArray.parseArray(entity.getEmployeeAllDayLongList(), EmployeeIdList.class);
            listList.forEach(l->{
                WorkEmployeeEntity e = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .eq(WorkEmployeeEntity::getCorpId,  CorpContextHolder.getCorpId())
                        .eq(WorkEmployeeEntity::getId, l.getId()));
                if (e != null){
                    EmployeeAllDayLongListByDetails dayLongList = new EmployeeAllDayLongListByDetails();
                    BeanUtil.copyProperties(e,dayLongList);
                    dayLongList.setEmployeeId(e.getId());
                    dayLongList.setEmployeeName(e.getName());
                    dayLongList.setStatus(l.getStatus());
                    allDayLongLists.add(dayLongList);
                }
            });
            vo.setEmployeeAllDayLongList(allDayLongLists);
        }else {
            LinkedList<EmployeeTopBottomLineListByDetails> bottomLineLists = new LinkedList<>();
            List<EmployeeTopBottomLineLists> topBottomLineLists = JSONArray.parseArray(entity.getEmployeeTopBottomLineList(), EmployeeTopBottomLineLists.class);
            topBottomLineLists.forEach(top->{
                List<Integer> empIds = new LinkedList<>();
                top.getEmployeeIdList().forEach(e->{
                    if (e.getStatus().equals(1)){
                        empIds.add(e.getId());
                    }
                });
                List<WorkEmployeeEntity> entities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .eq(WorkEmployeeEntity::getCorpId,  CorpContextHolder.getCorpId())
                        .in(WorkEmployeeEntity::getId, empIds));

                int i = DateUtil.dayOfWeek(new Date())-1;
                boolean flag = false;
                for (Integer week:top.getWeekList()){
                    if (week.equals(i)){
                        flag = true;
                        break;
                    }
                }
                LinkedList<EmployeeListByDetails> employeeListByDetails = new LinkedList<>();
                if (flag){
                    DateTime now = DateTime.now();
                    long time = now.getTime();
                    long startTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + top.getEmployeeTopBottomLineStartTime() + ":00").getTime();
                    long endTime = DateUtil.parseDateTime(DateUtil.now().split(" ")[0] + " " + top.getEmployeeTopBottomLineEndTime() + ":00").getTime();
                    if (time >= startTime && time <= endTime){
                        entities.forEach(en->{
                            EmployeeListByDetails details = new EmployeeListByDetails();
                            BeanUtil.copyProperties(en, details);
                            details.setEmployeeId(en.getId());
                            details.setEmployeeName(en.getName());
                            details.setStatus(1);
                            employeeListByDetails.add(details);
                        });
                    }else {
                        entities.forEach(en->{
                            EmployeeListByDetails details = new EmployeeListByDetails();
                            BeanUtil.copyProperties(en, details);
                            details.setEmployeeId(en.getId());
                            details.setEmployeeName(en.getName());
                            details.setStatus(2);
                            employeeListByDetails.add(details);
                        });
                    }
                }else {
                    entities.forEach(en->{
                        EmployeeListByDetails details = new EmployeeListByDetails();
                        BeanUtil.copyProperties(en, details);
                        details.setEmployeeId(en.getId());
                        details.setEmployeeName(en.getName());
                        details.setStatus(2);
                        employeeListByDetails.add(details);
                    });
                }
                EmployeeTopBottomLineListByDetails lineList = new EmployeeTopBottomLineListByDetails();
                BeanUtil.copyProperties(top,lineList);
                lineList.setEmployeeIdList(employeeListByDetails);
                bottomLineLists.add(lineList);
            });
            vo.setEmployeeTopBottomLineListByDetails(bottomLineLists);
        }

        //设置员工每日添加客户上限列表
        if(entity.getEmployeeAddUpperLimitStatus().equals(1)){
            List<EmployeeAddUpperLimitList> upperLimitLists = JSONArray.parseArray(entity.getEmployeeAddUpperLimitList(), EmployeeAddUpperLimitList.class);
            LinkedList<EmployeeAddUpperLimitListByDetails> employeeAddUpperLimitListByDetails = new LinkedList<>();
            upperLimitLists.forEach(up->{
                EmployeeAddUpperLimitListByDetails details = new EmployeeAddUpperLimitListByDetails();
                BeanUtil.copyProperties(up,details);
                WorkEmployeeEntity employeeEntity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .eq(WorkEmployeeEntity::getCorpId,  CorpContextHolder.getCorpId())
                        .eq(WorkEmployeeEntity::getId, up.getEmployeeId()));
                ChannelCodeContactStatisticsEntity one = channelCodeContactStatisticsService.getOne(Wrappers.<ChannelCodeContactStatisticsEntity>lambdaQuery()
                        .eq(ChannelCodeContactStatisticsEntity::getCorpId, entity.getCorpId())
                        .eq(ChannelCodeContactStatisticsEntity::getEmployeeId, employeeEntity.getId())
                        .eq(ChannelCodeContactStatisticsEntity::getChannelId, entity.getId())
                        .ge(BaseEntity::getCreateTime,DateUtil.beginOfDay(new Date()))
                        .le(BaseEntity::getCreateTime,DateUtil.endOfDay(new Date())));
                if (employeeEntity != null && one != null){
                    BeanUtil.copyProperties(employeeEntity,details);
                    details.setEmployeeId(employeeEntity.getId());
                    details.setEmployeeName(employeeEntity.getName());
                    details.setContactNum(one.getNewAddContact());
                    employeeAddUpperLimitListByDetails.add(details);
                }
            });
            vo.setEmployeeAddUpperLimitList(employeeAddUpperLimitListByDetails);
        }

        //设置备用员工列表
//        List<WorkEmployeeEntity> employeeEntities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
//                .eq(WorkEmployeeEntity::getCorpId,  CorpContextHolder.getCorpId())
//                .in(WorkEmployeeEntity::getId, JSONArray.parseArray(entity.getStandbyEmployeeList(), Integer.class)));
//        LinkedList<EmployeeListByDetails> employeeListByDetails = new LinkedList<>();
//        employeeEntities.forEach(em->{
//            EmployeeListByDetails details = new EmployeeListByDetails();
//            BeanUtil.copyProperties(em,details);
//            details.setEmployeeId(em.getId());
//            details.setEmployeeName(em.getName());
//            employeeListByDetails.add(details);
//        });
//        vo.setStandbyEmployeeList(employeeListByDetails);

        //设置自动通过好友值
        if (entity.getAutoAddFriendStatus().equals(1)){
            vo.setAutoAddFriendMsg(JSONObject.parseObject(entity.getAutoAddFriendMsg(), AutoAddFriendMsg.class));
        }

        //设置客户标签
        if (entity.getCustomerTagStatus().equals(1)){
            List<WorkContactTagUserGroupCreateDTO> dtos = JSONArray.parseArray(entity.getCustomerTagList(), WorkContactTagUserGroupCreateDTO.class);
            LinkedList<WorkContactTagCreateByChannelCodeDTO> createDTOS = new LinkedList<>();
            dtos.forEach(d->{
                WorkContactTagCreateByChannelCodeDTO dto = new WorkContactTagCreateByChannelCodeDTO();
                dto.setGroupId(d.getGroupId());
                dto.setGroupName(d.getGroupName());
                LinkedList<WorkContactTagByChannelCodeDTO> codeDTOS = new LinkedList<>();
                d.getTagNameList().forEach(tag->{
                    WorkContactTagByChannelCodeDTO codeDTO = new WorkContactTagByChannelCodeDTO();
                    WorkContactTagEntity one = workContactTagService.getOne(Wrappers.<WorkContactTagEntity>lambdaQuery()
                            .eq(WorkContactTagEntity::getCorpId,  CorpContextHolder.getCorpId())
//                            .eq(WorkContactTagEntity::getWxContactTagId, tag.getWxContactTagId())
                            .eq(WorkContactTagEntity::getId, tag.getId())
                    );
                    if (one != null){
                        codeDTO.setTagId(one.getId());
                        codeDTO.setName(one.getName());
                        codeDTO.setWxContactTagId(one.getWxContactTagId());
                        codeDTOS.add(codeDTO);
                    }
                });
                dto.setTagNameList(codeDTOS);
                createDTOS.add(dto);
            });
            vo.setCustomerTagList(createDTOS);
        }

        //设置渠道话术
        if (entity.getGreetingStatus().equals(1)){
            ChannelGreetingMsg msg = JSONObject.parseObject(entity.getChannelGreetingMsg(), ChannelGreetingMsg.class);
            ChannelGreetingMsgByDetails details = new ChannelGreetingMsgByDetails();
            BeanUtil.copyProperties(msg,details);
            MediumEnyity enyity = mediumService.getById(msg.getMediumId());
            if (enyity != null){
                details.setMedium(JSONArray.parseArray(enyity.getContent()));
            }
            vo.setChannelGreetingMsg(details);
        }

        //设置分时段话术
        if (entity.getDaypartingGreetingStatus().equals(1)){
            List<DaypartingGreetingList> greetingLists = JSONArray.parseArray(entity.getDaypartingGreetingList(), DaypartingGreetingList.class);
            LinkedList<DaypartingGreetingListByDetails> details = new LinkedList<>();
            greetingLists.forEach(g->{
                DaypartingGreetingListByDetails list = new DaypartingGreetingListByDetails();
                BeanUtil.copyProperties(g,list);
                MediumEnyity enyity = mediumService.getById(g.getMediumId());
                if (enyity != null){
                    list.setMedium(JSONArray.parseArray(enyity.getContent()));
                }
                details.add(list);
            });
            vo.setDaypartingGreetingList(details);
        } else {
            vo.setDaypartingGreetingList(null);
        }

        //设置欢迎语屏蔽词
        if(entity.getGreetingShieldStatus().equals(1)){
            vo.setGreetingShieldList(JSONArray.parseArray(entity.getGreetingShieldList(),String.class));
        }

        return vo;
    }

    @Override
    public boolean updateChannelCode(ChannelCodeUpdateDTO channelCodeUpdateDTO) {
        ChannelCodeEntity entity = getOne(Wrappers.<ChannelCodeEntity>lambdaQuery()
                .eq(ChannelCodeEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(ChannelCodeEntity::getId, channelCodeUpdateDTO.getId()));
        HashMap<String, List<?>> map = new HashMap<>();
        entity.setCorpId(CorpContextHolder.getCorpId());
        BeanUtil.copyProperties(channelCodeUpdateDTO, entity);
        preHandleUpdateDto(channelCodeUpdateDTO, entity);
        // 若客服人员状态为1-全天在线
        if (channelCodeUpdateDTO.getCustomerServicePersonnelStatus().equals(1)) {
            entity.setEmployeeTopBottomLineList(null);
            entity.setEmployeeAllDayLongList(JSONUtil.toJsonStr(channelCodeUpdateDTO.getEmployeeAllDayLongList()));
            List<EmployeeIdList> list = channelCodeUpdateDTO.getEmployeeAllDayLongList();
            List<Integer> empIds = new LinkedList<>();
            list.forEach(l -> {
                if (l.getStatus().equals(1)) {
                    empIds.add(l.getId());
                }
            });
            if (!empIds.isEmpty()) {
                List<WorkEmployeeEntity> entities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .in(WorkEmployeeEntity::getId, empIds)
                        .eq(WorkEmployeeEntity::getCorpId, CorpContextHolder.getCorpId())
                );
                List<String> eIds = new LinkedList<>();
                entities.forEach(e -> {
                    eIds.add(e.getWxUserId());
                });
                map.put("eIds", eIds);
            }
        } /*else {
            entity.setEmployeeTopBottomLineList(JSONUtil.toJsonStr(channelCodeUpdateDTO.getEmployeeTopBottomLineList()));
            entity.setEmployeeAllDayLongList(null);
            List<EmployeeTopBottomLineLists> lists = channelCodeUpdateDTO.getEmployeeTopBottomLineList();
            LinkedList<Integer> list = new LinkedList<>();
            lists.forEach(l -> {
                l.getEmployeeIdList().forEach(em -> {
                    if (em.getStatus().equals(1)) {
                        list.add(em.getId());
                    }
                });
            });
            List<Integer> collect = list.stream().distinct().collect(Collectors.toList());
            List<WorkEmployeeEntity> entities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .in(WorkEmployeeEntity::getId, collect)
                    .eq(WorkEmployeeEntity::getCorpId, CorpContextHolder.getCorpId()));
            List<String> eIds = new LinkedList<>();
            entities.forEach(e -> {
                eIds.add(e.getWxUserId());
            });
            map.put("eIds", eIds);
        }*/
        boolean save = updateById(entity);
        if (save) {
            workChannelCodeSyncLogic.onCreateWxAddContactWayQrcode(entity, map);
            updateChannelCodeQr(entity.getId(), entity.getCorpId());
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void exitImagesByZip(ChannelCodeExitImageDTO dto,HttpServletResponse response,OutputStream out) {
        if (dto.getType()!=null && dto.getType().equals(1)){
            List<ChannelCodeEntity> list = list(Wrappers.<ChannelCodeEntity>lambdaQuery().eq(ChannelCodeEntity::getCorpId,  CorpContextHolder.getCorpId()));
            List<Integer> channelId = new LinkedList<>();
            list.forEach(l->{
                channelId.add(l.getId());
            });
            dto.setChannelId(channelId);
        }
        List<Integer> collect = dto.getChannelId().stream().distinct().collect(Collectors.toList());
        log.info("collect:"+collect);
        try {
            List<ChannelCodeEntity> entities = list(Wrappers.<ChannelCodeEntity>lambdaQuery()
                    .eq(ChannelCodeEntity::getCorpId,  CorpContextHolder.getCorpId())
                    .in(ChannelCodeEntity::getId, collect));
            log.info("entities:"+entities);
            File [] files = new File[entities.size()];
            LinkedList<File> list = new LinkedList<>();
            entities.forEach(e->{
                File file = FilesUtil.getFileByURI(e.getQrcodeUrl());
                log.info("file:"+file);
                list.add(file);
            });
            log.info("list:"+list);
            list.toArray(files);
            log.info("files:"+ Arrays.toString(files));
            File zip = ZipUtil.zip(FileUtil.file(fileUploadConfig.getRealPath()+ File.separator+"批量下载渠道活码.zip"), false,files);
            log.info("zip:"+zip);
            BufferedInputStream inputStream = FileUtil.getInputStream(zip);
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bytes = IoUtil.readBytes(inputStream);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition","attachment;filename=exit.zip");
            outputStream.write(bytes);
            IoUtil.close(outputStream);
        }catch (Exception e){
            log.info("Exception:"+e.getLocalizedMessage());
            e.printStackTrace();
        }

    }

    @Override
    public ChannelCodeEntity getChannelCodeOne(Integer channelId, Integer corpId) {
        return baseMapper.getChannelCodeOne(channelId,corpId);
    }

    @Override
    public void saveTag(Integer corpId, Integer channelId, String externalUserid, Integer employeeId) {
        WorkContactEntity contactEntity = workContactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                .eq(WorkContactEntity::getCorpId, corpId)
                .eq(WorkContactEntity::getWxExternalUserid, externalUserid));
        Integer contactId = contactEntity.getId();
        ChannelCodeEntity entity = getOne(Wrappers.<ChannelCodeEntity>lambdaQuery()
                .eq(ChannelCodeEntity::getCorpId, corpId)
                .eq(ChannelCodeEntity::getId, channelId));
        if (entity != null){
            if (entity.getCustomerTagStatus().equals(1)){
                List<WorkContactTagUserGroupCreateDTO> dtos = JSONArray.parseArray(entity.getCustomerTagList(), WorkContactTagUserGroupCreateDTO.class);
                HashSet<Integer> tagsId = new HashSet<>();
                dtos.forEach(d->{
                    d.getTagNameList().forEach(t->{
                        WorkContactTagEntity one = workContactTagService.getOne(Wrappers.<WorkContactTagEntity>lambdaQuery()
                                .eq(WorkContactTagEntity::getCorpId, corpId)
//                                .eq(WorkContactTagEntity::getWxContactTagId, t.getWxContactTagId())
                                .eq(WorkContactTagEntity::getId, t.getId())
                        );
                        if (one != null){
                            tagsId.add(one.getId());
                        }
                    });
                });

                List<WorkContactTagPivotEntity> list = workContactTagPivotService.list(Wrappers.<WorkContactTagPivotEntity>lambdaQuery()
                        .eq(WorkContactTagPivotEntity::getEmployeeId, employeeId)
                        .eq(WorkContactTagPivotEntity::getContactId, contactId));
                HashSet<Integer> hashSet = new HashSet<>();
                list.forEach(l->{
                    hashSet.add(l.getContactTagId());
                });

                LinkedList<Integer> integers = new LinkedList<>();
                tagsId.removeAll(hashSet);
                integers.addAll(tagsId);

                if (integers != null){
                    LinkedList<WorkContactTagPivotEntity> entities = new LinkedList<>();
                    integers.forEach(i->{
                        WorkContactTagPivotEntity pivotEntity = new WorkContactTagPivotEntity();
                        pivotEntity.setEmployeeId(employeeId);
                        pivotEntity.setContactId(contactId);
                        pivotEntity.setContactTagId(i);
                        entities.add(pivotEntity);
                    });
                    workContactTagPivotService.saveBatch(entities);
                }

            }
        }

    }

    @Override
    public void updateRemarkAndDescription(Integer corpId, Integer channelId, String externalUserid, Integer employeeId) {

        ChannelCodeEntity codeEntity = getOne(Wrappers.<ChannelCodeEntity>lambdaQuery()
                .eq(ChannelCodeEntity::getCorpId, corpId)
                .eq(ChannelCodeEntity::getId, channelId));
        if (codeEntity != null){
            WorkContactEntity contactEntity = workContactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                    .eq(WorkContactEntity::getCorpId, corpId)
                    .eq(WorkContactEntity::getWxExternalUserid, externalUserid));
            WorkContactEmployeeEntity entity = new WorkContactEmployeeEntity();
            boolean flag = false;
            if (codeEntity.getClientDescriptionStatus().equals(1)){
                log.info("getClientDescriptionStatus:"+codeEntity.getClientDescriptionStatus());
                entity.setDescription(codeEntity.getClientDescriptionMsg());
                flag = true;
            }
            if (codeEntity.getCustomerRemarksStatus().equals(1)){
                log.info("getCustomerRemarksStatus:"+codeEntity.getCustomerRemarksStatus());
                entity.setRemark(contactEntity.getName()+"-"+codeEntity.getCustomerRemarksMsg());
                flag = true;
            }
            if (flag){
                QueryWrapper<WorkContactEmployeeEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("employee_id",employeeId);
                wrapper.eq("contact_id",contactEntity.getId());
                wrapper.eq("corp_id",corpId);
                workContactEmployeeService.update(entity,wrapper);
                //修改企业微信客户备注信息
                externalContactService.updateRemark(employeeId, corpId, contactEntity.getId(), entity.getRemark(), entity.getDescription());
            }
        }


    }

    /**
     * 渠道活码与渠道活码分组列表
     * @param keyWords
     * @return
     */
    @Override
    public List<ChannelCodeListVO> getList(String keyWords) {
        Integer corpId = CorpContextHolder.getCorpId();
        List<ChannelCodeListVO> vos = new LinkedList<>();
        if (StrUtil.isBlank(keyWords)){
            List<ChannelCodeGroupEntity> groupEntities = channelCodeGroupService.list(Wrappers.<ChannelCodeGroupEntity>lambdaQuery()
                    .eq(ChannelCodeGroupEntity::getCorpId, corpId));
            groupEntities.forEach(g->{
                ChannelCodeListVO vo = new ChannelCodeListVO();
                List<ChannelCodeListCCVO> ccvos = new LinkedList<>();
                vo.setGroupName(g.getName());
                vo.setGroupId(g.getId());
                List<ChannelCodeEntity> list = list(Wrappers.<ChannelCodeEntity>lambdaQuery()
                        .eq(ChannelCodeEntity::getCorpId, corpId)
                        .eq(ChannelCodeEntity::getGroupId, g.getId()));
                vo.setCount(list.size());
                list.forEach(l->{
                    ChannelCodeListCCVO ccvo = new ChannelCodeListCCVO();
                    ccvo.setChannelId(l.getId());
                    ccvo.setChannelName(l.getName());
                    ccvos.add(ccvo);
                });
                vo.setChannelCodeListCCVOList(ccvos);
                vos.add(vo);
            });
        }else {
            List<ChannelCodeGroupEntity> groupEntities = channelCodeGroupService.list(Wrappers.<ChannelCodeGroupEntity>lambdaQuery()
                    .eq(ChannelCodeGroupEntity::getCorpId, corpId));
            groupEntities.forEach(g->{
                ChannelCodeListVO vo = new ChannelCodeListVO();
                LinkedList<ChannelCodeListCCVO> ccvos = new LinkedList<>();
                List<ChannelCodeEntity> list = list(Wrappers.<ChannelCodeEntity>lambdaQuery()
                        .eq(ChannelCodeEntity::getCorpId, corpId)
                        .eq(ChannelCodeEntity::getGroupId,g.getId())
                        .like(ChannelCodeEntity::getName, keyWords));
                if (!list.isEmpty()){
                    vo.setGroupName(g.getName());
                    vo.setGroupId(g.getId());
                    vo.setCount(list.size());
                    list.forEach(l->{
                        ChannelCodeListCCVO ccvo = new ChannelCodeListCCVO();
                        ccvo.setChannelId(l.getId());
                        ccvo.setChannelName(l.getName());
                        ccvos.add(ccvo);
                    });
                    vo.setChannelCodeListCCVOList(ccvos);
                    vos.add(vo);
                }
            });

        }

        return vos;
    }

    /**
     * 获取当前渠道活码及渠道活码分组所有成员列表
     * @param dto
     * @return
     */
    @Override
    public List<ChannelCodeEmployeeListVO> getChannelCodeEmployeeList(ChannelCodeEmployeeListDTO dto) {
        Integer corpId = CorpContextHolder.getCorpId();
        HashSet<Integer> channelIds = new HashSet<>();
//        if (dto.getGroupIds() != null){
//            dto.getGroupIds().forEach(g->{
//                List<ChannelCodeEntity> entities = list(Wrappers.<ChannelCodeEntity>lambdaQuery()
//                        .eq(ChannelCodeEntity::getCorpId, corpId)
//                        .eq(ChannelCodeEntity::getGroupId, g));
//                entities.forEach(e->{
//                    channelIds.add(e.getId());
//                });
//            });
//        }
        List<Integer> groupIds = dto.getGroupIds();
        if (groupIds != null && groupIds.size() > 0){
            List<ChannelCodeEntity> entities = list(Wrappers.<ChannelCodeEntity>lambdaQuery()
                    .eq(ChannelCodeEntity::getCorpId, corpId)
                    .in(ChannelCodeEntity::getGroupId, groupIds));
            entities.forEach(e->{
                channelIds.add(e.getId());
            });
        }
        if(dto.getChannelIds() != null) {
            channelIds.addAll(dto.getChannelIds());
//            dto.getChannelIds().forEach(c->{
//                channelIds.add(c);
//            });
        }
        List<Integer> channelId = new LinkedList<>(channelIds);

        LinkedList<ChannelCodeEmployeeListVO> vos = new LinkedList<>();
        //判断当前是否有需要模糊搜索的成员名
        if (StrUtil.isBlank(dto.getName())){
//            QueryWrapper<ChannelCodeContactStatisticsEntity> wrapper = new QueryWrapper<>();
//            wrapper.select("employee_id");
//            wrapper.eq("corp_id",corpId);
//            wrapper.in("channel_id",channelId);
//            wrapper.groupBy("employee_id");
//            List<ChannelCodeContactStatisticsEntity> allEmployee = channelCodeContactStatisticsService.list(wrapper);

            List<ChannelCodeContactStatisticsEntity> allEmployee = channelCodeContactStatisticsService.list(
                    Wrappers.<ChannelCodeContactStatisticsEntity>lambdaQuery()
                            .select(ChannelCodeContactStatisticsEntity::getEmployeeId)
                            .eq(ChannelCodeContactStatisticsEntity::getCorpId, corpId)
                            .in(ChannelCodeContactStatisticsEntity::getChannelId, channelId)
                            .groupBy(ChannelCodeContactStatisticsEntity::getEmployeeId)
            );

//            QueryWrapper<ChannelCodeContactStatisticsEntity> queryWrapper = new QueryWrapper<>();
//            queryWrapper.select("employee_id");
//            queryWrapper.ge("create_time",DateUtil.beginOfDay(new Date()));
//            queryWrapper.le("create_time",DateUtil.endOfDay(new Date()));
//            queryWrapper.eq("corp_id",corpId);
//            queryWrapper.in("channel_id",channelId);
//            queryWrapper.groupBy("employee_id");
//            List<ChannelCodeContactStatisticsEntity> employee = channelCodeContactStatisticsService.list(queryWrapper);
            Date now = new Date();
            List<ChannelCodeContactStatisticsEntity> employee = channelCodeContactStatisticsService.list(
                    Wrappers.<ChannelCodeContactStatisticsEntity>lambdaQuery()
                    .select(ChannelCodeContactStatisticsEntity::getEmployeeId)
                    .ge(ChannelCodeContactStatisticsEntity::getCreateTime, DateUtil.beginOfDay(now))
                    .le(ChannelCodeContactStatisticsEntity::getCreateTime, DateUtil.endOfDay(now))
                    .eq(ChannelCodeContactStatisticsEntity::getCorpId, corpId)
                    .in(ChannelCodeContactStatisticsEntity::getChannelId, channelId)
                    .groupBy(ChannelCodeContactStatisticsEntity::getEmployeeId)
            );

            //判断是否有不在渠道活码中的成员
            if (employee.size() == allEmployee.size()){
                employee.forEach(e->{
                    ChannelCodeEmployeeListVO vo = new ChannelCodeEmployeeListVO();
                    WorkEmployeeEntity entity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                            .eq(WorkEmployeeEntity::getCorpId, corpId)
                            .eq(WorkEmployeeEntity::getId, e.getEmployeeId()));
                    if (entity != null){
                        vo.setAvatar(entity.getAvatar());
                        vo.setEmployeeId(entity.getId());
                        vo.setName(entity.getName());
                        if (entity.getStatus() == 5){
                            vo.setIsResign(2);
                        }else {
                            vo.setIsResign(1);
                        }
                        vo.setIsBackup(1);
                        vos.add(vo);
                    }
                });
            }else {
                //当有不在渠道中的成员时
                AtomicBoolean flag = new AtomicBoolean(false);
                allEmployee.forEach(all->{
                    flag.set(false);
                    for (ChannelCodeContactStatisticsEntity c:employee) {
                        if (all.getEmployeeId().equals(c.getEmployeeId())){
                            ChannelCodeEmployeeListVO vo = new ChannelCodeEmployeeListVO();
                            WorkEmployeeEntity entity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                    .eq(WorkEmployeeEntity::getCorpId, corpId)
                                    .eq(WorkEmployeeEntity::getId, all.getEmployeeId()));
                            if (entity != null){
                                vo.setAvatar(entity.getAvatar());
                                vo.setEmployeeId(entity.getId());
                                vo.setName(entity.getName());
                                if (entity.getStatus() == 5){
                                    vo.setIsResign(2);
                                }else {
                                    vo.setIsResign(1);
                                }
                                vo.setIsBackup(1);
                                vos.add(vo);
                            }
                            flag.set(true);
                            break;
                        }
                    }
                    if (flag.get()){
                        ChannelCodeEmployeeListVO vo = new ChannelCodeEmployeeListVO();
                        WorkEmployeeEntity entity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getCorpId, corpId)
                                .eq(WorkEmployeeEntity::getId, all.getEmployeeId()));
                        if (entity != null){
                            vo.setAvatar(entity.getAvatar());
                            vo.setEmployeeId(entity.getId());
                            vo.setName(entity.getName());
                            if (entity.getStatus() == 5){
                                vo.setIsResign(2);
                            }else {
                                vo.setIsResign(1);
                            }
                            vo.setIsBackup(1);
                            vos.add(vo);
                        }
                    }
                });
            }
        }else {
            List<WorkEmployeeEntity> employeeEntities = workEmployeeService.list(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                    .eq(WorkEmployeeEntity::getCorpId, corpId)
                    .like(WorkEmployeeEntity::getName, dto.getName()));
            List<Integer> employeeList = new LinkedList<>();
            employeeEntities.forEach(e->{
                employeeList.add(e.getId());
            });
            if (employeeList != null){
                QueryWrapper<ChannelCodeContactStatisticsEntity> wrapper = new QueryWrapper<>();
                wrapper.select("employee_id");
                wrapper.eq("corp_id",corpId);
                wrapper.in("channel_id",channelId);
                wrapper.groupBy("employee_id");
                List<ChannelCodeContactStatisticsEntity> allEmployee = channelCodeContactStatisticsService.list(wrapper);

                QueryWrapper<ChannelCodeContactStatisticsEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.select("employee_id");
                queryWrapper.ge("create_time",DateUtil.beginOfDay(new Date()));
                queryWrapper.le("create_time",DateUtil.endOfDay(new Date()));
                queryWrapper.eq("corp_id",corpId);
                queryWrapper.in("channel_id",channelId);
                queryWrapper.groupBy("employee_id");
                List<ChannelCodeContactStatisticsEntity> employee = channelCodeContactStatisticsService.list(queryWrapper);

                List<Integer> list1 = new LinkedList<>();
                List<Integer> list2 = new LinkedList<>();
                allEmployee.forEach(e->{
                    list1.add(e.getEmployeeId());
                });
                employee.forEach(e->{
                    list2.add(e.getEmployeeId());
                });

                list1.retainAll(employeeList);
                list2.retainAll(employeeList);

                //判断是否有不在渠道活码中的成员
                if (list1.size() == list2.size()){
                    list1.forEach(e->{
                        ChannelCodeEmployeeListVO vo = new ChannelCodeEmployeeListVO();
                        WorkEmployeeEntity entity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getCorpId, corpId)
                                .eq(WorkEmployeeEntity::getId, e));
                        if (entity != null){
                            vo.setAvatar(entity.getAvatar());
                            vo.setEmployeeId(entity.getId());
                            vo.setName(entity.getName());
                            if (entity.getStatus() == 5){
                                vo.setIsResign(2);
                            }else {
                                vo.setIsResign(1);
                            }
                            vo.setIsBackup(1);
                            vos.add(vo);
                        }
                    });
                }else {
                    //当有不在渠道中的成员时
                    AtomicBoolean flag = new AtomicBoolean(false);
                    list1.forEach(all->{
                        flag.set(false);
                        for (Integer c:list2) {
                            if (all.equals(c)){
                                ChannelCodeEmployeeListVO vo = new ChannelCodeEmployeeListVO();
                                WorkEmployeeEntity entity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                        .eq(WorkEmployeeEntity::getCorpId, corpId)
                                        .eq(WorkEmployeeEntity::getId, allEmployee));
                                if (entity != null){
                                    vo.setAvatar(entity.getAvatar());
                                    vo.setEmployeeId(entity.getId());
                                    vo.setName(entity.getName());
                                    if (entity.getStatus() == 5){
                                        vo.setIsResign(2);
                                    }else {
                                        vo.setIsResign(1);
                                    }
                                    vo.setIsBackup(1);
                                    vos.add(vo);
                                }
                                flag.set(true);
                                break;
                            }
                        }
                        if (flag.get()){
                            ChannelCodeEmployeeListVO vo = new ChannelCodeEmployeeListVO();
                            WorkEmployeeEntity entity = workEmployeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                    .eq(WorkEmployeeEntity::getCorpId, corpId)
                                    .eq(WorkEmployeeEntity::getId, all));
                            if (entity != null){
                                vo.setAvatar(entity.getAvatar());
                                vo.setEmployeeId(entity.getId());
                                vo.setName(entity.getName());
                                if (entity.getStatus() == 5){
                                    vo.setIsResign(2);
                                }else {
                                    vo.setIsResign(1);
                                }
                                vo.setIsBackup(1);
                                vos.add(vo);
                            }
                        }
                    });
                }
            }
        }

        return vos;
    }


}
